<template>
  <div class="home">
    <!--  opacity:0.3;  -->
    <el-card class="box-card"  v-show="bubbleInfoDialog.open" shadow="always" style=" position: absolute;width:300px;background-color: #9cccfacc;color: #666666">
      <div  class="text item">{{'片名：' + bubbleInfoDialog.bubble.name }}</div>
      <div  class="text item">{{'上映日期：' + bubbleInfoDialog.bubble.showTime }}</div>
      <div  class="text item">{{'产地：' + bubbleInfoDialog.bubble.area }}</div>
      <div  class="text item">{{'时长：' + bubbleInfoDialog.bubble.duration }}</div>
      <div  class="text item">{{'评分：' + bubbleInfoDialog.bubble.score }}</div>
      <div  class="text item">{{'标题：' + bubbleInfoDialog.bubble.title }}</div>
      <!--      <div  class="text item">{{'简介：' + bubbleInfoDialog.bubble.introduction }}</div>-->
    </el-card>
    <audio
      ref="audioPlayer"
      src="../../../assets/audio/bubbling.mp3"
    ></audio>
    <!--    <audio loop src="../assets/audio/bubbling.mp3" autoplay="autoplay"  loop="loop" preload="auto"></audio>-->
    <!--    <audio loop :src="musicSrc" autoplay="autoplay"  loop="loop" preload="auto"></audio>-->
    <!--    <audio ref="audioPlayer" :src="musicSrc" loop autoplay="autoplay" loop="loop" preload="auto"></audio>-->

    <div class="btn-group" >
      <div class="miracle-btn-light" @click="nextPage"><span>换一批</span></div>
      <div class="miracle-btn-light" @click="speedMusic" title="多次点击调节速度"><span>倍速</span></div>
      <div class="miracle-btn-light"  title="暂停/播放" @click="playOrPause">
        <span v-show="!musicIsPlay" >播放</span >
        <span v-show="musicIsPlay" >暂停</span >
      </div>
      <div class="miracle-btn-light" @click="volMusic" title="加速增加"><span>音量</span></div>
      <div class="miracle-btn-light" @click="test"><span>测试</span></div>
    </div>
    <ul id="ball-box">
      <li v-for="(item, index) in bubbleData" :key="index" :class="{'active': item.is_active}">
        <a>
          <div @click="showBubbleInfo(item)" >
            <span>{{ item.name }}</span>
          </div>
        </a>
      </li>
    </ul>
  </div>

</template>

<script>

export default {
  name: 'float-bubble',
  props: {
    // 小球数据
    rawData: {
      type: Array,
      require: true,
      default: () => []
    },
    //小球颜色
    bubbleColors : {
      type: Array,
      require: false,
      default: () => [
        "#FF0033",
        "#CC00FF",
        "#3300FF",
        "#FFCC00",
        "#FF6600",
        "#33CC33",
        "#00FFFF",
        "#99FF33",
        "#9900FF",
        "#33CCCC",
      ],
    },
  },
  data() {
    return {
      bubbleInfoDialog:{
        // 是否显示弹出层
        open: false,
        bubble: {},
      },
      //起始位置，结束位置，长度
      bubbleRange:[0, 0, 20],
      //小球数据（name:名称，is_active:是否展示，colorIdx：颜色）
      bubbleData: [],
      bubbleDom: [],
      bubbleArr: [],
      //初始化运动的最大宽和高，初始定义0
      maxW: 0,
      maxH: 0,
      //小球定时器
      timerArr: [],
      musicSrc: "../../../assets/audio/bubbling.mp3",
      musicIsPlay: false,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.nextPage();
      this.initMusic();
    });
  },
  methods: {
    initMusic: function (){
      //若支持自动播放则自动播放，否则给出提示。
      let passage_audio = this.$refs.audioPlayer;
      passage_audio.load();//	重新加载音频元素。
      passage_audio.playbackRate = 0.75;//设置或返回音频播放的速度 def:1
      passage_audio.volume = 0.02;//设置或返回音频的音量 def:1
      passage_audio.loop = true;//设置或返回音频是否应在结束时再次播放
      passage_audio.play()//开始播放音频。
      .then(() => {
          // 支持自动播放
        console.log(Math.round(passage_audio.duration));//返回音频的长度（以秒计）
      }).catch(err => {
        // 不支持自动播放
        this.$modal.msgWarning("不支持自动播放，可点击播放按钮播放音频");
      }).finally(()=>{
        let paused = passage_audio.paused;//设置或返回音频是否暂停。
        if (paused){
          this.musicIsPlay = false;
        }else {
          this.musicIsPlay = true;
        }
      });
    },
    // 播放音乐
    speedMusic: function (){
      let passage_audio = this.$refs.audioPlayer;
      passage_audio.play();

      let musicSpeed = passage_audio.playbackRate >= 2.5 ? 0.5 : passage_audio.playbackRate + 0.25;
      passage_audio.playbackRate = musicSpeed;//设置或返回音频播放的速度
      this.$modal.msgSuccess("当前播放速度："+passage_audio.playbackRate);
    },
    // 暂停音乐
    playOrPause: function (){
      let passage_audio = this.$refs.audioPlayer;
      let paused = passage_audio.paused;//设置或返回音频是否暂停。
      if (paused){
        passage_audio.play();//	播放当前播放的音频。
      }else {
        passage_audio.pause();//	暂停当前播放的音频。
      }
      this.musicIsPlay = !this.musicIsPlay;
      this.$modal.msgSuccess(this.musicIsPlay==true?"开始播放":"已暂停");
    },
    //设置音量
    volMusic: function (){
      let passage_audio = this.$refs.audioPlayer;
      let vol = passage_audio.volume;
      if (passage_audio.volume<0.1){
        vol = (vol*100 + 2)/100;
      } else if (0.1<=passage_audio.volume && passage_audio.volume<0.4){
        vol = (vol*100 + 10)/100;
      }else if (0.4<=passage_audio.volume && passage_audio.volume<1){
        vol = (vol*100 + 20)/100 > 1 ? 1 : (vol*100 + 20)/100;
      }else if (passage_audio.volume==1){
        vol = 0.02;
      }
      passage_audio.volume = vol;
      this.$modal.msgSuccess("当前播放音量："+passage_audio.volume);
    },
    test(){

    },
    /**
     * 翻页,超过数据长度时重新循环
     */
    nextPage(){
      if ( this.rawData.length < this.bubbleRange[2] ) console.error("data error：%o<%o",this.rawData.length,this.bubbleRange[2]);
      let fst = this.bubbleRange[1];
      let snd = this.bubbleRange[1] + this.bubbleRange[2];
      snd = snd >= this.rawData.length ?  (snd - this.rawData.length) : snd;

      this.bubbleRange = [fst, snd, this.bubbleRange[2]];
      let tmp;
      if ( fst > snd ) {
        //重新循环
        tmp = this.rawData.slice(this.bubbleRange[0], this.rawData.length).concat(this.rawData.slice(0, snd));
      } else {
        tmp = this.rawData.slice(this.bubbleRange[0],this.bubbleRange[1])
      }
      this.bubbleData = tmp.map(e=>{
        e.is_active = true;
        e.colorIdx = Math.round(Math.random()*(this.bubbleColors.length-1));
        return e;
      });
      this.refreshBubble();
    },
    /**
     * 刷新
     */
    refreshBubble() {
      this.clearData();
      this.$nextTick(() => {
        if (this.bubbleData.length) {
          this.initBubble()
        }
      });

    },
    /**
     * 展示明细
     * @param bubble
     */
    showBubbleInfo(bubble){
      this.bubbleInfoDialog.bubble = bubble;
      this.bubbleInfoDialog.open = true;
      setTimeout(function (){
        this.bubbleInfoDialog.open = false;
      }.bind(this),200000);
    },
    clearData(){
      //清理每个球得定时器，让球停下来
      this.timerArr.forEach(item => {
        clearInterval(item);
      });
      //清理数据
      this.timerArr = [];
      this.bubbleDom = [];
      this.bubbleArr = [];
    },
    /**
     * 检测新增加的节点，初始化球的状态
     */
    initBubble() {
      let ballBox = document.getElementById("ball-box");
      let divDom = ballBox.getElementsByClassName("active"); //获取新增加的dom
      if (!divDom.length) {
        return;
      }
      //给新增加的dom设置宽高
      for (let i = 0; i < divDom.length; i++) {
        divDom[i].style.boxShadow = "0 0 20px" + " " + this.bubbleColors[this.bubbleData[i].colorIdx] + " " + "inset";
        // 10个以上尺寸变小
        divDom[i].style.width = "46px";
        divDom[i].style.height = "46px";
        divDom[i].style.fontSize = "12px";
        divDom[i].style.lineHeight = "12px";
        this.bubbleDom.push(divDom[i])
      }

      //根据浏览器窗口的大小自动调节小球的运动空间
      window.onresize = () => {
        this.maxW = ballBox.clientWidth - divDom[0].clientWidth; //为了让小球不卡在浏览器边缘
        this.maxH = ballBox.clientHeight - divDom[0].clientHeight; // 所以要减去自身的宽高
      };
      onresize();

      //数组对象的初始化
      for (let i = 0; i < this.bubbleDom.length; i++) {
        let obj = {};
        if (this.bubbleDom[i].getAttribute("class") === 'active') {
          obj.x = Math.floor(Math.random() * (this.maxW + 1)); //初始x坐标
          obj.y = Math.floor(Math.random() * (this.maxH + 1)); //初始y坐标
          obj.cx = obj.x + this.bubbleDom[0].offsetWidth / 2;//圆心x坐标
          obj.cy = obj.y + this.bubbleDom[0].offsetHeight / 2;//圆心y坐标
          obj.movex = Math.floor(Math.random() * 2); //x轴移动方向
          obj.movey = Math.floor(Math.random() * 2); //y轴移动方向
          obj.speed = 1; //随机速度
          obj.timer = null; //计时器
          obj.index = i; //索引值
          this.bubbleArr.push(obj)
          //小球位置初始化
          this.bubbleDom[i].style.left = obj.x + 'px';
          this.bubbleDom[i].style.top = obj.y + 'px';
        } else {
          //保留之前数据得位置信息，不刷新位置
          obj = this.bubbleArr[i]
        }
        this.move(obj);
      }
    },

    //移动函数
    move(balls) {
      //每个球单独有定时器
      balls.timer = setInterval(() => {
        if (balls.movex === 1) {
          //如果往右跑，则一直加速度，碰到边界，改为反方向运动
          balls.x += balls.speed;
          if (balls.x + balls.speed >= this.maxW) {
            //防止小球出界
            balls.x = this.maxW;
            balls.movex = 0; //小球运动方向发生改变
          }
        } else {
          balls.x -= balls.speed; // 1和0表示正反方向
          if (balls.x - balls.speed <= 0) {
            balls.x = 0;
            balls.movex = 1;
          }
        }
        if (balls.movey === 1) {
          balls.y += balls.speed;
          if (balls.y + balls.speed >= this.maxH) {
            balls.y = this.maxH;
            balls.movey = 0;
          }
        } else {
          balls.y -= balls.speed;
          if (balls.y - balls.speed <= 0) {
            balls.y = 0;
            balls.movey = 1;
          }
        }
        if (this.bubbleDom[balls.index]) {
          balls.cx = balls.x + this.bubbleDom[0].offsetWidth / 2;//小球圆心等于：运动中x的值加上自身的半径
          balls.cy = balls.y + this.bubbleDom[0].offsetHeight / 2;
          this.bubbleDom[balls.index].style.left = balls.x + "px"; //小球相对于屏幕的位置
          this.bubbleDom[balls.index].style.top = balls.y + "px";
          this.crash(balls.index); //每个小球进行碰撞检测
        }
      }, 25);
      this.timerArr.push(balls.timer)
    },
    //碰撞函数
    crash(a) {
      let container = [...this.bubbleArr]
      let ball1x = container[a].cx; //在数组中任意球的圆心坐标
      let ball1y = container[a].cy;//思路：先随便拿一个球，然后遍历所有球，拿这个球和所有球的圆心距离比较
      for (let i = 0; i < container.length; i++) {
        if (i !== a) { //判断取出来的球不是本身，才能和其他球进行距离判断
          let ball2x = container[i].cx; //将其他球的圆心坐标赋值给球2
          let ball2y = container[i].cy;
          //圆心距 求两个点之间的距离,开平方
          let distence = Math.sqrt((ball1x - ball2x) * (ball1x - ball2x) + (ball1y - ball2y) * (ball1y - ball2y));
          if (distence <= this.bubbleDom[0].offsetWidth) { //球心距离和求直径比较
            if (ball1x > ball2x) { //当前位于未知求的右方
              if (ball1y > ball2y) {//预设未知球撞当前球，然后当前球改变运动
                container[a].movex = 1; //1表示为正值，对应的右和下
                container[a].movey = 1;//0表示为负值，对应的左和上
              } else if (ball1y < ball2y) {
                container[a].movex = 1;
                container[a].movey = 0;
              } else {
                container[a].movex = 1;
              }
            } else if (ball1x < ball2x) {
              if (ball1y > ball2y) {
                container[a].movex = 0;
                container[a].movey = 0;
              } else if (ball1y < ball2y) {
                container[a].movex = 0;
                container[a].movey = 1;
              } else {
                container[a].movex = 0;
              }
            } else {
              if (ball1y > ball2y) {
                container[a].movey = 1;
              } else if (ball1y < ball2y) {
                container[a].movey = 0;
              }
            }
          }
        }
      }
    }
  },
  beforeDestroy() {
    //清理每个球得定时器
    this.timerArr.forEach(item => {
      clearInterval(item)
    })
  }
};
</script>


<style rel="stylesheet/scss" lang="scss">
@import '../../../assets/styles/miracle/miracle-btn.scss';
html,body{
  height: 100%;
  width: 100%;
}
.home{
  width: 100%;
  height: 100%;
  position: absolute;
  //background: #00afff;
  background-image: url("../../../assets/images/idx.jpg");
  background-size: cover;
}
.btn-group{
  position: absolute;
  width: 100px;
  left: 48%;
}
#ball-box {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
  margin: 0;
  padding: 0;

  li {
    position: absolute;
    overflow: hidden;
    -moz-border-radius: 50%;
    -webkit-border-radius: 50%;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;

    &.active {
      animation: scaleBox 1s 1;
    }

    @keyframes scaleBox {
      0% {
        transform: scale(1);
      }
      50% {
        transform: scale(1.2);
      }
      100% {
        transform: scale(1);
      }
    }

    div {
      span {
        display: block;
        width: 100%;
        color: #fff;
        text-align: center;
      }
    }
  }
}

</style>
